﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using BabyFood.Entities;
using BabyFood.Data;

public partial class DangNhap : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["KhachHangVip"] != null)
        {
            Response.Redirect("~/");
        }
    }
    protected void cmdDangNhap_Click(object sender, ImageClickEventArgs e)
    {
        string strUserName = Common.StandardString(txtTenTruyCap.Text);
        string strPassWord = Common.StandardString(txtMatKhau.Text);
        string strUserCode = strUserName + strPassWord;
        strPassWord = Common.EncryptMD5(strPassWord);
        strUserCode = Common.EncryptMD5(strUserCode);
        DoLogin(strUserName, strPassWord, strUserCode);
    }

    public void DoLogin(string strUserName, string strPassword, string strUserCode)
    {
        KhachHang entKhachHang = DataRepository.KhachHangProvider.GetByTenTruyCap(strUserName);
        if (entKhachHang == null)
        {
            WebMessage.Show("Người dùng không tồn tại trong hệ thống, Xin vui lòng thử lại");
            txtTenTruyCap.Focus();
            return;
        }

        string CurrentPassword = entKhachHang.MatKhau;
        string CurrentUserCode = entKhachHang.MaTruyCap;
        string strPassWord = Common.StandardString(txtMatKhau.Text);
        if (strPassword.Equals(CurrentPassword) && strUserCode.Equals(CurrentUserCode))
        {
            string strUserInfor = string.Format("{0};{1};{2}", entKhachHang.Id, entKhachHang.TenTruyCap, entKhachHang.HoTen);
            Session["KhachHangVip"] = entKhachHang.HoTen;
            FormsAuthentication.SetAuthCookie(strUserInfor, false);
            Response.Redirect("~/");
        }
        else
        {
            WebMessage.Show("Mật khẩu không đúng, Xin vui lòng thử lại");
            txtMatKhau.Focus();
            return;
        }
    }
}